package com.atguigu.dao.impl;

import com.atguigu.dao.UserDao;
import com.atguigu.pojo.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * dao层类 持久化层asd
 * 操作数据库，依赖QueryRunner类
 */
public class UserDaoImpl implements UserDao {
    //不要new对象，通过配置文件对象，注入进来
    private QueryRunner qr;
    public UserDaoImpl(QueryRunner qr){
        this.qr=qr;
    }

    /**
     * 删除数据
     * @param id
     * @return
     * @throws SQLException
     */
    @Override
    public int deleteUser(int id) throws SQLException {
        //拼写sql语句
        String sql = "delete from user where id = ?";
        return qr.update(sql,id);
    }

    /**
     * 更新数据
     * @param user
     * @return
     * @throws SQLException
     */
    @Override
    public int updateUser(User user) throws SQLException {
        //拼写sql语句
        String sql = "update user set username=?,sex=?,birthday=?,address=? where id=?";
        //取出User对象中的参数，
        Object[] params = {user.getUsername(),user.getSex(),user.getBirthday(),user.getAddress(),user.getId()};
        return qr.update(sql,params);
    }

    /**
     * 新增数据
     * 要新增的数据，存JavaBean对象
     * @param user
     * @return
     * @throws SQLException
     */
    @Override
    public int insertUser(User user) throws SQLException {
        //拼写SQL语句
        String sql = "insert into user values(?,?,?,?,?)";
        //取出User对象中的参数，
        Object[] params = {null,user.getUsername(),user.getSex(),user.getBirthday(),user.getAddress()};
        return qr.update(sql,params);
    }

    /**
     * 查询全表数据
     * @return
     * @throws SQLException
     */
    @Override
    public List<User> queryUser() throws SQLException {
        //拼写sql语句
        String sql = "select * from user";
        //QueryRunner qr对象执行sql语句
        //查询结果集封装对象 BeanListHandler
        return qr.query(sql,new BeanListHandler<User>(User.class));
    }
}
